package com.jqlin.mybatis.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jqlin.mybatis.domain.User;
import com.jqlin.mybatis.log.LogUtil;
import com.jqlin.mybatis.service.UserService;

@Controller
@RequestMapping("/user") //默认会加上.do路径
public class UserAction {
	
	/**
	 * 一、servlet get, post请求分发模式
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method=RequestMethod.GET)
	public String doGet(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("get");
		String username = (String) request.getParameter("username");
		System.out.println(username);
		//null时，取这个user为中缀，加前缀后缀形成返回视图的路径。
		return null; // null时
		//返回list的相关jsp
		//return "list";
	} 
	
	@RequestMapping(method= RequestMethod.POST)
	public String doPost(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("post");
		return "jsp/list"; 
	}

	/**
	 * 二、请求分发方式：类struts1
	 */
	@RequestMapping(params="method=add")
	public String add(String username){
		System.out.println("add");
		System.out.println(username);
		return "jsp/list";
	}
	
	
	/**
	 * 三、路径请求分发：类似struts2
	 */
	//user 和likeStruts2是父子的关系  
    @RequestMapping("/likeStruts2")
    public String likeStruts2(User user) {
        System.out.println("likeStruts2");
        System.out.println(user.getUserName());
        return "jsp/list";
    }
    
	
    /**
     * 重定向
     */
    @RequestMapping(params="method=redirectUrl")
    public String redirectUrl(){
    		
    		System.out.println("redirect...");
    		return  "redirect:http://www.baidu.com"; //重定向
    }
    
    /**
     * 请求转发
     */
    @RequestMapping(params="method=forwardUrl")
    public String forwardUrl() {
    		
    		System.out.println("forward..");
//    		return  "forward:user.do?method=add"; //重定向
    		return  "forward:user/likeStruts2"; //重定向
    }


    /**
     * request.session
     */
    @RequestMapping(params="method=reqSession")
    public String reqSession(String userName,HttpServletRequest req){
        req.setAttribute("a", "aa");
        req.getSession().setAttribute("b", "bb");
        return null;
    }

    /**
     * modelView
     * @param userName
     * @return
     */
//    @RequestMapping(value="modelView")两种写法都可以
    @RequestMapping("/modelView")
	public ModelAndView modelView(String userName) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("jsp/mv");;
		
		mv.addObject("msg", "helloKitty");
		
		List<String> l1 = new ArrayList<String>();
		l1.add("l1");
		l1.add("l2");
		l1.add("l3");
		mv.addObject("list",l1);
		
		Map<String, String> m = new HashMap<String, String>();
		m.put("m1", "bj");
		m.put("m2", "sh");
		m.put("m3", "gz");
		mv.addObject("map", m);
		
		User u = new User();
		u.setUserName("haha");
		mv.addObject("u", u);
		
		return mv;
	}
    
    /**
     * 上传
     * @param userName
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/upload")
    public String upload(String userName, @RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) {
    		System.out.println(userName);
    		if(!file.isEmpty()) {
    				ServletContext servletContext = request.getSession().getServletContext();
    				String path = servletContext.getRealPath("/upload/");  //获取本地存储路径
                System.out.println(path);
                String fileName = file.getOriginalFilename();
                String fileType = fileName.substring(fileName.lastIndexOf("."));
                System.out.println(fileType); 
                File file2 = new File(path,System.currentTimeMillis()+ (int)(Math.random()*(1000-100+1)+100) + fileType); //新建一个文件
                try {
                     file.getFileItem().write(file2); //将上传的文件写入新建的文件中
                } catch (Exception e) {
                     e.printStackTrace();
                }
    		}
    		
    		return "index";
    }
    
    
    /**
     * json
     * @param args
     */
    @RequestMapping(params="method=myajax",method=RequestMethod.GET)
    public @ResponseBody List<User> myajax(String userName) throws Exception{ 
        String uname2 = new String(userName.getBytes("iso8859-1"),"utf-8");
        System.out.println(uname2);
        List<User> list = new ArrayList<User>();
        list.add(new User("h1", 1));
        list.add(new User("h2", 2));
        return list;
    }
    
    /**
     * 测试调用mybatis接口
     * @param args
     */
    @RequestMapping(params="method=login")
    public @ResponseBody Map login(int id) throws Exception{ 
    		LogUtil.infoLogger(UserAction.class, "id==>" + id);
        User user = this.userService.selectUserByID(id);
        Map m  = new HashMap();
        m.put("status", "success");
        m.put("user", user);
        return m;
    }
    
    
    private UserService userService;


	public UserService getUserService() {
		return userService;
	}

	@Resource
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
    
    
    
}
